package me.skyun.androidarch.connect;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

import java.io.IOException;
import java.util.UUID;

import me.skyun.androidarch.common.Utils;

/**
 * Created by skyun on 17/8/21.
 */

public class BluetoothServer extends ConnServer<BluetoothServerSocket, BluetoothSocket> {

    private String mName;
    private UUID mUuid;

    public BluetoothServer(String name, UUID uuid, Callback serverCallback, Connection.Callback connectionCallback) {
        super(serverCallback, connectionCallback);
        mName = name;
        mUuid = uuid;
    }

    public void startListen() {
        start();
    }

    @Override
    protected BluetoothServerSocket createListenSocket() {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (!adapter.isEnabled()) {
            adapter.enable();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (mListenSocket == null) {
            try {
                mListenSocket = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(mName, mUuid);
            } catch (IOException e) {
                Utils.logMsg("Failed to start server");
            }
        }
        return mListenSocket;
    }

    @Override
    protected BluetoothSocket accept() throws IOException {
        return mListenSocket.accept();
    }

    @Override
    protected String getAddress(BluetoothSocket conSock) {
        return conSock.getRemoteDevice().getAddress();
    }
}
